package com.rongxun.hbwallet.mvp.presenter;

import android.content.Context;
import android.support.annotation.NonNull;

import com.rongxun.base.BaseObserver;
import com.rongxun.base.BasePresenter;
import com.rongxun.hbwallet.R;
import com.rongxun.hbwallet.constants.HttpConstants;
import com.rongxun.hbwallet.constants.SPKey;
import com.rongxun.hbwallet.model.entity.PostCodeLoginInfo;
import com.rongxun.hbwallet.model.bean.User;
import com.rongxun.hbwallet.mvp.contract.ILogin;
import com.rongxun.utils.ALog;
import com.rongxun.utils.JsonUtils;
import com.rongxun.utils.PreferenceUtils;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 创建者     庄丰泽
 * 创建时间   2018/8/17 15:41
 * 描述	      登录
 */
public class LoginPresenter extends BasePresenter<ILogin.IView, ILogin.IModel> implements ILogin.IPresenter {
    public LoginPresenter(@NonNull ILogin.IView pUi, @NonNull ILogin.IModel pModel) {
        super(pUi, pModel);
    }
    @Override
    public void login(String phone_number, String password) {
        if(phone_number.isEmpty()){
            getView().showError(getView().getContext().getString(R.string.input_mobile_code),"");
        }
        if(password.isEmpty()){
            getView().showError(getView().getContext().getString(R.string.please_input_password),"");
        }
        PostCodeLoginInfo info=new PostCodeLoginInfo();
        info.setMobile(phone_number);
        info.setMode("password");
        info.setPassword(password);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), JsonUtils.toJson(info));
        addSubscribe(getModel().Login(requestBody).subscribeWith(new BaseObserver<User>(getView()){
            @Override
            public void onSuccess(User user, Context context) {
                saveUserInfo(user);
            }}
        ));
    }
    @Override
    public void saveUserInfo(User user) {
        if(user!=null){
            String token = user.getToken();

            String id=user.getUserInfo().getId();
            PreferenceUtils.put(SPKey.USER, JsonUtils.toJson(user));
            PreferenceUtils.put(SPKey.TOKEN, HttpConstants.Token_hold+token);
            ALog.i("Mytoken",HttpConstants.Token_hold+token);
            PreferenceUtils.put(SPKey.USERID, id);
            ALog.i("MyUserid",id);
            getView().showLogin();
        }
    }
}
